{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pinecone-io/examples/blob/master/learn/experimental/algos-and-libraries/bertopic/01_topic_modeling.ipynb) [![Open nbviewer](https://raw.githubusercontent.com/pinecone-io/examples/master/assets/nbviewer-shield.svg)](https://nbviewer.org/github/pinecone-io/examples/blob/master/learn/experimental/algos-and-libraries/bertopic/01_topic_modeling.ipynb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install bertopic"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will use the r/python data downloaded before. If loading from file:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "data = pd.read_csv('python.csv', sep='|')\n",
    "```\n",
    "\n",
    "Otherwise, load directly from HuggingFace Hub like so:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using custom data configuration jamescalam--reddit-python-107f1094f98d4fba\n",
      "Reusing dataset json (/Users/jamesbriggs/.cache/huggingface/datasets/json/jamescalam--reddit-python-107f1094f98d4fba/0.0.0/ac0ca5f5289a6cf108e706efcf040422dbbfa8e658dee6a819f20d76bb84d26b)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Dataset({\n",
       "    features: ['sub', 'title', 'selftext', 'upvote_ratio', 'id', 'created_utc'],\n",
       "    num_rows: 933\n",
       "})"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from datasets import load_dataset\n",
    "\n",
    "data = load_dataset('jamescalam/reddit-python', split='train')\n",
    "data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's remove rows where `selftext` is *NaN* or very short. If using dataframe use:\n",
    "\n",
    "```python\n",
    "data = data[data['selftext'].str.len() > 30].reset_index()\n",
    "```\n",
    "\n",
    "Else..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading cached processed dataset at /Users/jamesbriggs/.cache/huggingface/datasets/json/jamescalam--reddit-python-107f1094f98d4fba/0.0.0/ac0ca5f5289a6cf108e706efcf040422dbbfa8e658dee6a819f20d76bb84d26b/cache-093f5a73cbc33e37.arrow\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Dataset({\n",
       "    features: ['sub', 'title', 'selftext', 'upvote_ratio', 'id', 'created_utc'],\n",
       "    num_rows: 622\n",
       "})"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = data.filter(lambda x: True if len(x['selftext']) > 30 else 0)\n",
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Batches:   5%|▌         | 1/20 [00:07<02:17,  7.21s/it]\n"
     ]
    }
   ],
   "source": [
    "from bertopic import BERTopic\n",
    "from sklearn.feature_extraction.text import CountVectorizer\n",
    "\n",
    "# we add this to remove stopwords, for lower volumes of data stopwords can cause issues\n",
    "vectorizer_model = CountVectorizer(ngram_range=(1, 2), stop_words=\"english\")\n",
    "\n",
    "# deal with df if needed\n",
    "if type(data['selftext']) is list:\n",
    "    text = data['selftext']\n",
    "else:\n",
    "    text = data['selftext'].tolist()\n",
    "\n",
    "model = BERTopic(\n",
    "    vectorizer_model=vectorizer_model,\n",
    "    language='english', calculate_probabilities=True,\n",
    "    verbose=True\n",
    ")\n",
    "topics, probs = model.fit_transform(text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This returns two lists, `topics` contains a one-to-one mapping of our titles to topic numbers, and `probs` contains a list of probabilities of a thread belonging to each topic (based on its `selftext`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(5):\n",
    "    print(f\"{topics[i]}: {data['selftext'][i]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can see the top words found in each topic using `get_topic_info`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "freq = model.get_topic_info()\n",
    "freq.head(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The top `-1` topic is generally assumed to be irrelevant, if we hadn't used the `vectorizer_model` this would typically be full of stopwords. In our case this seems to be the *\"most generic\"* of topics, about Python, code, and data.\n",
    "\n",
    "We can also visualize how related topics are using `visualize_topics`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.visualize_topics()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.visualize_hierarchy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.visualize_barchart()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13 (default, Mar 28 2022, 06:59:08) [MSC v.1916 64 bit (AMD64)]"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "5fe10bf018ef3e697f9035d60bf60847932a12bface18908407fd371fe880db9"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
